<?php
/**
 * 盘点方案
 * Created by PhpStorm.
 * User: echa
 * Date: 2018/4/11
 * Time: 10:11
 */
namespace App\Services\Warehouse;
use App\Repositories\Warehouse\WarehouseRepository;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class StockCountSchemeService extends PublicService{
    protected $WarehouseRepository;
    protected $InventoryOperationService;
    public function __construct(WarehouseRepository $warehouseRepository,InventoryOperationService $inventoryOperationService)
    {
        parent::__construct(config('k3cloud.StockCountScheme'));
        $this->WarehouseRepository=$warehouseRepository;
        $this->InventoryOperationService=$inventoryOperationService;
    }

    public function SaveStockCountScheme($arrdata=[],$is_submitandaudit=false){
        if(empty($arrdata['FID'])){
            $arrdata['FID']="0";
        }
        if(empty($arrdata['FBillNo'])){
            $arrdata['FBillNo']="";
        }
        if(empty($arrdata['FName'])){
            $arrdata['FName']=$arrdata['goods_sn'];
        }
        if(empty($arrdata['FCheckQtyDefault'])){
            $arrdata['FCheckQtyDefault']="0";
        }else{
            $arrdata['FCheckQtyDefault']="1";
        }
        if(empty($arrdata['FNote'])){
            $arrdata['FNote']="";
        }
        $field=array();
        $fieldwhere='(   ';
        $flas=true;
        if(!empty($arrdata['StockNumber'])){
            $flas=false;
            $field[]=[
                "Left"=>"",
                "FieldName"=>"FStockId.FNumber",
                "Compare"=>"67",
                "Value"=>$arrdata['StockNumber'],
                "Right"=>"",
                "Logic"=>"AND",
                "LogicName"=>"AND"
            ];
            $fieldwhere.="FStockId.FNumber = N'".$arrdata['StockNumber']."' AND    ";
        }
        if(!empty($arrdata['goods_sn'])){
            $flas=false;
            $field[]=[
                "Left"=>"",
                "FieldName"=>"FMaterialId.FNumber",
                "Compare"=>"67",
                "Value"=>$arrdata['goods_sn'],
                "Right"=>"",
                "Logic"=>"AND",
                "LogicName"=>"AND"
            ];
            $fieldwhere.="FMaterialId.FNumber = N'".$arrdata['goods_sn']."' AND    ";
        }
        /*$FOwnerTypeBDSupplier=config('k3cloud.FOwnerTypeBDSupplier');
        $FOwnerTypeBDOwnerOrg=config('k3cloud.FOwnerTypeBDOwnerOrg');
        $FOwnerIdHead=config('k3cloud.organization');
        $FOwnerTypeIdHead=$FOwnerTypeBDOwnerOrg;
        if(!empty($arrdata['k3_vmi'])){
            $FOwnerTypeIdHead=$FOwnerTypeBDSupplier;
            $FOwnerIdHead=$arrdata['k3_supplier_sn'];
        }
        if(isset($arrdata['k3_vmi'])){
            $flas=false;
            $field[]=[
                "Left"=>"",
                "FieldName"=>"FOwnerTypeId",
                "Compare"=>"29",
                "Value"=>$FOwnerTypeIdHead,
                "Right"=>"",
                "Logic"=>"AND",
                "LogicName"=>"AND"
            ];
            $fieldwhere.="FOwnerTypeId = N'".$FOwnerTypeIdHead."' AND    ";
        }
        if(isset($arrdata['k3_supplier_sn'])){
            $flas=false;
            $field[]=[
                "Left"=>"",
                "FieldName"=>"FOwnerId.FNumber",
                "Compare"=>"67",
                "Value"=>$FOwnerIdHead,
                "Right"=>"",
                "Logic"=>"AND",
                "LogicName"=>"AND"
            ];
            $fieldwhere.="FOwnerTypeId = N'".$FOwnerIdHead."' AND    ";
        }*/
        if($flas){
            throw new NotFoundHttpException('请输入盘点方案过滤条件');
        }
        $fieldwhere=substr($fieldwhere,0,strlen($fieldwhere)-7)."   )";
        $fieldstr=json_encode($field);
        $data=[
            "FID"=>$arrdata['FID'],
            "FBillTypeID"=>[
                "FNumber"=>"PDFA01_SYS"
            ],
            "FBillNo"=>$arrdata['FBillNo'],
            "FName"=>$arrdata['FName'],
            "FStockOrgId"=>[
                "FNumber"=>config('k3cloud.organization')
            ],
            "FDocumentStatus"=>"Z",
            "FNote"=>$arrdata['FNote'],
            "FCloseStatus"=>"0",
            "FBackUpDATE"=>"1900-01-01",
            "FZeroStockInCount"=>false,
            "FAllowAddMaterial"=>true,
            "FCheckQtyDefault"=>$arrdata['FCheckQtyDefault'],
            "FOWnerTypeID"=>"",
            "FOwnerId"=>[
                "FNumber"=>""
            ],
            "FStockId"=>[
                "FNumber"=>""
            ],
            "FMaterialId"=>[
                "FNumber"=>""
            ],
            "FKeeperTypeId"=>"",
            "FKeeperId"=>[
                "FNumber"=>""
            ],
            "FStockIdTo"=>[
                "FNumber"=>""
            ],
            "FMaterialIdTo"=>[
                "FNumber"=>""
            ],
            "FBackUpType"=>"Inventory",
            "FFILTERSETTING"=>$fieldstr,
            "FFILTERSTRING"=>$fieldwhere
        ];
        $IsSuccess=true;
        if($is_submitandaudit){
            $return=$this->save($data);
            if(empty($return['Id'])){
                return false;
            }
            $submitreturn=$this->SubmitStockCountScheme([$return['Number']]);
            if(empty($submitreturn['Id'])){
                $IsSuccess=false;
                return ['Data'=>$return,'IsSuccess'=>$IsSuccess,'status'=>1]; //单据属于创建状态
            }
            $auditreturn=$this->AuditStockCountScheme([$return['Number']]);
            if(empty($auditreturn['Id'])){
                $IsSuccess=false;
                return ['Data'=>$submitreturn,'IsSuccess'=>$IsSuccess,'status'=>2];//单据属于审核中状态
            }
            return ['Data'=>$auditreturn,'IsSuccess'=>$IsSuccess]; //单据属于审核通过状态
        }else{
            return $this->save($data);
        }

    }

    /**
    提交
     *
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */

    public function  SubmitStockCountScheme($Numbers=[]){
        return $this->submit($Numbers);
    }

    /**
    审核
     * 1.formid：业务对象表单Id（必录）
    2.data：Json格式数据（详情参考Json格式数据）（必录）
    2.1.CreateOrgId：创建者组织，字符串类型（非必录）
    2.2.Numbers：单据编号集合，格式["billNo1","billNo1",...]，数组类型（必录）
     */
    public function AuditStockCountScheme($Numbers=[]){
        return $this->audit($Numbers);
    }

    /***
     * 创建盘点方案
     * @param array $data
    @author echa
     * @return array|bool|mixed
     */
    public function CreateStockCountScheme(array $data){
        if(empty($data['wid'])){
            return false;
        }
        $winfo=$this->WarehouseRepository->GetWarehouseInfo($data['wid']);
        if(empty($winfo['k3_number'])){
            return false;
        }
        //主仓库编号
        $k3_number=$winfo['k3_number'];
        $postdata=[
            'goods_sn'=>$data['goods_sn'],
            'StockNumber'=>$k3_number,
            'FNote'=>$data['note']
        ];
        $return=$this->SaveStockCountScheme($postdata);
        if(!$return){
            return false;
        }
        return $return;
    }

    /***
     * 盘点方案提交并审核以及查询对应物料盘点作业单据明细
     * @param string $Numbers
    @author echa
     * @return array|bool|mixed
     */
    public function SubmitAndAuditStockCountSchemeAndIO($Numbers=''){
        $submitreturn=$this->SubmitStockCountScheme([$Numbers]);
        if(empty($submitreturn['Id'])){
            return false;
        }
        $auditreturn=$this->AuditStockCountScheme([$Numbers]);
        if(empty($auditreturn['Id'])){
            return false;
        }
        $scsNumber=$auditreturn['Number'];
        $ioreturn=$this->InventoryOperationService->ViewSourceGoodsInventoryOperation($scsNumber);
        if($ioreturn){
            return $ioreturn;
        }else{
            return false;
        }
    }

}